<template>
<view class="week-task">
	<view class="task-top">
		<view :class="{'task-top-fixed': !accountId}">
			<view class="ac-list">
                    <text class="ac-item" :class="{active: tabIndex==ac.state}" v-for="(ac, inx) in tabs" :key="inx" @click="tabClick(ac.state)">{{ac.name}}</text>
                </view>
			<view class="task-top-line"></view>
		</view>
	</view>
	<view class="create-course-box">
		<view class="scroll-y">
			<view v-if="tabIndex==0" style="padding: 0 32rpx 20rpx;">
				<view class="task-content" v-for="(item, inx) in taskList" :key="inx">
					<view class="cont-title">
						<text class="title">{{item.title}}</text>
						<text class="state" :class="[{state1: handleState(item.taskUser)==1, state2: handleState(item.taskUser)==2}]">{{handleState(item.taskUser)==2?'已完成':handleState(item.taskUser)==1?'待审核':'待完成'}}</text>
					</view>
					<view class="task-desc">
						<text class="desc">{{item.content.length>45?`${item.content.slice(0, 41)}...`:item.content}}</text>
				
						<view class="see" @click="seeDetails(item)"><text>查看详情</text>
						<uni-icons type="right" color="#999"></uni-icons></view>

					</view>
					<view v-if="!item.taskUser">
						<view class="textarea-box">
							<text-editor :id-name="`editor${inx}`" :week-task="inx" :info="{content: item.inputContent, placeText: '请填写任务详情', showUpload: false}" @chooseFile="chooseFile" @editorInput="editorInput" @closePopup="getIndex"></text-editor>
							<view class="all-img-file" v-if="fils[`editor${inx}`]">
								<view class="imgs" v-if="fils[`editor${inx}`].sendimgs">
									<view class="img-box" v-for="(file, i) in fils[`editor${inx}`].sendimgs" :key="i">
										<image class="img" :src="api.xiaodeObsUrl+file.path" mode="aspectFill"></image>
										<image class="close" @click="delFiles(i, fils[`editor${inx}`].sendimgs)" src="/static/chat/close.png" mode="aspectFill"></image>
									</view>
								</view>
								<view class="files" v-if="fils[`editor${inx}`].sendfiles">
									<view class="file-box" v-for="(item, i) in fils[`editor${inx}`].sendfiles" :key="i">
										<zy-file :src="item.path" :name="item.name" :size="item.size"></zy-file>
										<image class="close" @click="delFiles(i, fils[`editor${inx}`].sendfiles)" src="/static/chat/close.png" mode="aspectFill"></image>
									</view>
									
								</view>
							</view>
							<view class="tips">
								<text>*需上传图片</text>
							</view>
						</view>
					</view>
					<view v-else>
						<view class="textarea-box1">
							<text-editor :id-name="`editorList${inx}`" :read-only="true" 
									:info="{content: item.taskUser.content, height: 'auto'}"></text-editor>
							<view class="all-img-file 1">
								<view class="imgs">
									<view class="img-box" v-for="(path, i) in item.dst_imgs" :key="i">
										<image class="img" :src="path" mode="aspectFill" @click="previewImage(item.dst_imgs, i)"></image>
									</view>
								</view>
								<view class="files">
									<view class="file-box" v-for="(file, i) in item.files" :key="i">
										<zy-file :src="file.path" :name="file.name" :size="file.size"></zy-file>
									</view>
									
								</view>
							</view>
						</view>
					</view>
					<view class="time-publish">
						<text>{{!item.taskUser?'活动时间':'发布时间'}}：{{handleTime(item)}}</text>
						<view v-if="!item.taskUser" class="pub-btn" :style="{opacity: item.inputContent&&currentIndex==`editor${inx}`?1:.3}" @click="submitTask(item)">立即发布</view>
					</view>
					<view class="eva-content" v-if="item.state==2">
						<view class="tea-info">
							<image :src="item.teaPic?api.xiaodeObsUrl+item.teaPic:'/static/te1.png'" mode="aspectFill"></image>
							<text>{{item.teaName}}</text>
						</view>	
						<view class="eva-score">
							<image :src="`/static/score${i<=item.score_teacher?1:''}.png`" v-for="i in 3" :key="i" mode="aspectFill"></image>
						</view>
						<view class="eva-text">
							{{item.evaluate_content}}
						</view>
					</view>
				</view>
				<view class="no-task" v-if="taskList.length==0">暂无任务</view>
			</view>
			<daily-labor v-if="tabIndex==1"
				:on-reach-bottom="onReachBottom"
				:account-id="accountId"
				:student-id="studentId"
				:on-show="onShow"
			></daily-labor>
			<take-exercise v-if="tabIndex==2"
				:on-reach-bottom="onReachBottom"
				:account-id="accountId"
				:on-show="onShow"
			></take-exercise>
			<example-task v-if="tabIndex==3"
				:on-reach-bottom="onReachBottom"
				:account-id="accountId"
				:student-id="studentId"
				:on-show="onShow"
			></example-task>
			<active-overview v-if="tabIndex==4"
				:on-reach-bottom="onReachBottom"
				:account-id="accountId"
				:on-show="onShow"
			></active-overview>
			<active-track v-if="tabIndex==5"
				:on-reach-bottom="onReachBottom"
				:account-id="accountId"
				:on-show="onShow"
			></active-track>
		</view>
	</view>
</view>
</template>
<script>
	
import uploadFile from "./upload-file.vue"
import dailyLabor from "./daily-labor.vue"
import exampleTask from "./example-task.vue"
import takeExercise from './take-exercise.vue'
import activeOverview from './active-overview.vue'
import activeTrack from './active-track.vue'
import textEditor from './text-editor.vue'
export default {
    components: {
		uploadFile,
		dailyLabor,
		exampleTask,
		takeExercise,
		activeOverview,
		activeTrack,
		textEditor
    },
    props: {
		onShow: { // 监听页面执行onShow
			type: Number,
			default: 0
		},
		onReachBottom: { // 监听页面上滑
			type: Number,
			default: 0
		},
		activeTab: {
			type: Number,
			default: 0
		},
		accountId: { // 账号ID
			type: String,
			default: ''
		},
		studentId: { // 学生ID
			type: String,
			default: ''
		}
    },
    data() {
        return {
			taskContent: '',
			tabIndex: 0, // 对应tabs的state
			tabs: [{
					state: 0,
					name: '任务',
				},
				{
					state: 1,
					name: '劳动'
				},
				{
					state: 2,
					name: '锻炼'
				},
				{
					state: 3,
					name: '重要他人'
				},
				{
					state: 4,
					name: '活动概览'
				},
				{
					state: 5,
					name: '轨迹'
				},],
			taskList: [],
			// 上传文件和表情
			userId: -1,
			showUpload: false,
			focus: false,
			editorInfos: {},
			fils: {},
			currentIndex: '', // 当前任务下标
			currentPage: 1, // 当前页
            
        }
    },
	
	watch: {
		onShow(val){
			if(this.tabIndex == 0){
				
				this.initData()
			}
		},
		onReachBottom(val){
			if(this.tabIndex == 0  && this.loadMore == 'more'){
				this.currentPage ++
				this.getfindTask()
			}
		}
	},
    mounted(){
		this.userId = uni.getStorageSync('tokenObj').userId
		this.tabIndex = this.activeTab
		this.initData()
    },
    methods: {
		initData(){
			this.currentPage = 1
			this.taskList = []
			this.getfindTask()
		},
		getIndex(name){
			this.currentIndex = name
		},
		handleState(item){
			if(!item) return
			let state = item.state;
			let stateVal = item ? state==1 ? 1 : state==2 ? 2 : 0: 0;
			return stateVal
		},
		handleTime(item){
			let time = item.taskUser ? item.taskUser.add_time : item.update_time;
			time = time?time.split(' ')[0].split('-').join('.'):''
			return time
		},
		getfindTask(){
			this.loadMore = 'loading'
			let path = '',
			params = {
				isMy: false,
                page: this.currentPage,
                limit: 10
			}
			// 账号id存在，请求用户的任务列表
			if(this.accountId){
				path = 'ordinary/findUserTaskPage'
				params.accountId = this.accountId
			}else{
				path = 'ordinary/findTaskPage'
			}
			this.api.get(path, params).then(res=>{
				if(res.data.state != 'ok') return;
				this.loadMore = 'more'
				let taskPage = params.accountId?res.data.taskUserPage:res.data.taskPage;
				this.taskList = this.taskList.concat(taskPage.list)
				for(let i=0; i<taskPage.list.length; i++){

					if(taskPage.list[i].taskUser){
						this.handleFilesShow(taskPage.list[i].taskUser.files, i, taskPage.list[i].taskUser)
					}
					
				}
				this.showRequest = true
				if(taskPage.totalPage <= this.currentPage){
					this.loadMore = 'no-more'
				}
			})
		},
		submitTask(item){
			let info = this.fils[this.currentIndex] || {}
			let img = info.sendimgs || [],
			files = info.sendfiles || []
			let list = img.concat(files)
	
			// return
			if(!item.inputContent){
				this.utils.showToast('请填写任务详情')
				return
			}
			if(img.length==0) {
				this.utils.showToast('需上传图片')
				return
			}
			this.api.post('ordinary/commitTask', {
				taskId: item.id,
				content: item.inputContent,
				files: JSON.stringify(list)
			}).then(res=>{
				if(res.data.state!='ok') return
				this.utils.showToast('发布成功')
				item.inputContent = ''
				setTimeout(()=>{
					this.initData()
				}, 1000)
				
			})
		},
		tabClick(i){
			this.tabIndex = i
			if(i==0){
				this.initData()
			}
		},
		seeDetails(item){
			// uni.setStorageSync('taskDetailsInfo', item)
			let taskId = item.taskUser?item.taskUser.id:item.id
			uni.navigateTo({
				url: `/pages/student/task-details?taskId=${taskId}&trajectory=${item.taskUser?1:''}`
			})
		},
		bindfocus(e){
			this.showUpload = true
		},
		bindblur(e){
			this.taskContent = JSON.stringify(e.detail.delta.ops)
			window.scroll(0,0);
		},
		bindinput(e){
			
			this.taskContent = JSON.stringify(e.detail.delta.ops)
		},
		onEditorReady(e){
				uni.createSelectorQuery().select('#editor').context((res) => {
				this.editorCtx = res.context
			}).exec()
		},
		editorInput(inx, str, type){
			
			// return
			let info = this.taskList[inx];
			let cont = info.inputContent || ''
			if(type=='bq'){
				cont += str
			}else{
				cont = str
			}
			
			info.inputContent = cont
			this.$set(this.taskList, inx, info)

		},
		chooseFile(type, list, sendList){
			let info = this.fils[this.currentIndex] || {}
			let sendimgs = info.sendimgs || [],
				sendfiles = info.sendfiles || []
			if(type==1){
				sendimgs = sendimgs.concat(sendList)
				if(sendimgs.length>9){
					this.utils.showToast('最多可以上传9张图片')
					sendimgs.splice(9)
				}
			}else{
				sendfiles = sendfiles.concat(sendList)
				if(sendfiles.length>3){
					this.utils.showToast('最多可以上传3个文件')
					sendfiles.splice(3)
				}
			}
			info.sendimgs = sendimgs
			info.sendfiles = sendfiles
			this.$set(this.fils, this.currentIndex, info)
	
			
		},
		closePopup(){
			this.showUpload = false
		},
		// 获取下载链接
		
		handleFilesShow(list, index, item){
			list = JSON.parse(list)

			let imgs = [], files = [], dst_files = []
			for(let i=0; i<list.length; i++){
				if(list[i].msgType==8){
					files.push(list[i])
					dst_files.push(list[i])
				}else{
					imgs.push(`${this.api.xiaodeObsUrl}${list[i].path}`)
				}
				
			}
			let obj = this.taskList[index]
			obj.files = dst_files
			obj.dst_imgs = imgs
			this.$set(this.taskList, index, obj)

		},
		delFiles(i, sendItem){
			sendItem.splice(i, 1)
			let obj = this.fils[this.currentIndex]
			this.$set(this.fils, this.currentIndex, obj)
		},
		previewImage(list, i){
			uni.previewImage({
				current: i,
				urls: list,
				longPressActions: {
					itemList: [],
					success: function(data) {
						
					},
					fail: function(err) {
						// console.log(err.errMsg);
					}
				}
			});
		},
    }
}
</script>
<style scoped lang="less">
	.task-top{
		height: 76rpx;
		
	}
	.task-top-fixed{
		position: fixed;
		/* #ifdef H5 */
		top: 88rpx;
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		/* #ifndef H5 */
		top: calc(88rpx + 27px);
		left: 0;
		right: 0;
		/* #endif */
		z-index: 1;
	}
	.task-top-line{
		height: 36rpx;
		border-radius: 32rpx 32rpx 0 0;
		background-color: #fff;
	}
	.ac-list{
        margin-top: 43rpx;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 0 32rpx;
    }
    .ac-item{
        color: #666;
        font-size: 28rpx;
        padding-bottom: 20rpx;
        &.active{
            color: #262E3F;
            font-weight: bold;
            background-image: url(~@/static/campus/line-bg.png);
            background-size: 45rpx 18rpx;
            background-repeat: no-repeat;
            background-position: center 26rpx;
        }
    }
	.create-course-box{
		background-color: #fff;
		overflow: hidden;
		border-radius: 32rpx 32rpx 0 0;
		padding: 32rpx 0 0;
	}
	.task-content{
		margin-top: 20rpx;
		padding: 40rpx 0;
		background-color: #fff;
	}
	.cont-title{
		display: flex;
		justify-content: space-between;
		font-weight: 600;
		.title{
			width: 80%;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			font-size: 32rpx;
			color: #333333;
		}
		.state{
			position: relative;
			padding-left: 20rpx;
			color: #28C2CD;
			font-size: 24rpx;
			line-height: 32rpx;
			&::after{
				position: absolute;
				content: '';
				width: 10rpx;
				height: 10rpx;
				border-radius: 50%;
				top: 12rpx;
				left: 0%;
				// transform: translateY(-5rpx);
				background-color: #28C2CD;
			}
		}
		.state1{
			color: #FF4F01;
			&::after{
				background-color: #FF4F01;
			}
		}
		.state2{
			color: #999999;
			&::after{
				background-color: #999;
			}
		}
	}
	.task-desc{
		margin-top: 24rpx;
		line-height: 44rpx;
		color: #666666;
		.see{
			float: right;
			color: #999999;
		}
	}
	.textarea-box{
		margin-top: 32rpx;
		background-color: #F4F4F4;
		border-radius: 20rpx;
		padding: 32rpx;
		.tips{
			margin-top: 32rpx;
			font-size: 24rpx;
			color: #999;
		}
	}
	textarea{
		width: 100%;
		font-size: 28rpx;
	}
	.time-publish{
		margin-top: 24rpx;
		color: #999;
		font-size: 24rpx;
	}
	.pub-btn{
		margin-top: 32rpx;
		height: 80rpx;
		line-height: 80rpx;
		color: #fff;
		border-radius: 20rpx;
		background-color: #28C2CD;
		font-size: 32rpx;
		text-align: center;
	}
	.textarea-box1{
		margin-top: 32rpx;
		border-radius: 20rpx;
		border: 1rpx solid #EEEEEE;
		padding: 32rpx;
		.content{
			p{
				display: flex;
				align-items: center;
				flex-wrap: wrap;
			}
		}
	}
	.all-img-file{
		margin-top: 32rpx;
		font-size: 0;
		.img{
			width: 194rpx;
			height: 194rpx;
			margin-right: 20rpx;
			border-radius: 8rpx;
			margin-bottom: 20rpx;
			&:nth-child(3n){
				margin-right: 0;
			}
		}
		.img-box{
			display: inline-block;
			width: 194rpx;
			height: 194rpx;
			position: relative;
			margin-right: 18rpx;
			margin-bottom: 20rpx;
			&:nth-child(3n){
				margin-right: 0;
			}
		}
		.close{
			position: absolute;
			top: 0;
			right: 0;
			width: 40rpx;
			height: 40rpx;
		}
		.file-box{
			margin-top: 32rpx;
			width: 560rpx;
			position: relative;
		}
		.files{
			margin-top: 12rpx;
		}
	}
	.eva-content{
		margin-top: 64rpx;
		position: relative;
		&::after{
			position: absolute;
			left: 0;
			top: -32rpx;
			content: '';
			width: 200%;
			border-width: 2rpx;
			border-style: dashed;
			border-color: #000;
			transform: scale(0.5) translateX(-50%);
            opacity: .1;
		}
	}
	.tea-info{
		display: flex;
		align-items: center;
		color: #333333;
		image{
			width: 78rpx;
			height: 78rpx;
			border-radius: 156rpx;
			margin-right: 24rpx;
		}
	}
	.eva-score{
		margin: 24rpx 0;
		image{
			margin-right: 17rpx;
			width: 34rpx;
			height: 32rpx;
		}
	}
	.eva-text{
		color: #666666;
		font-size: 28rpx;
		line-height: 44rpx;
	}
	.no-task{
		height: calc(100vh - 178rpx);
		// #ifdef H5
		height: calc(100vh - 50px - 178rpx);
		// #endif
		display: flex;
		justify-content: center;
		align-items: center;
	}
</style>